using Microsoft.UI;
using Microsoft.UI.Text;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace WinUITest.Pages
{
    [Menu("富文本")]
    public sealed partial class RichEditBoxPage : Page
    {
        private readonly List<string> _regions = [];
        private readonly List<string> _performers = [];
        private readonly List<string> _spells = [];
        private readonly DispatcherTimer _timer;
        public RichEditBoxPage()
        {
            InitializeComponent();
            _timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(300)
            };
            _timer.Tick += Timer_Tick;
            _timer.Start();
        }
        private async void Timer_Tick(object? sender, object e)
        {
            _timer.Stop();
            try
            {
                await UpdateTextAsync();
            }
            finally
            {
                _timer.Start();
            }
        }
        private async Task UpdateTextAsync()
        {
            int index = editor.Document.Selection.GetIndex(TextRangeUnit.Character) - 1;
            if (index <= 0) return;
            int startIndex = index - 20;
            if (startIndex < 0)
            {
                startIndex = 0;
            }
            int endIndex = index + 20;
            ITextRange textRange = editor.Document.GetRange(startIndex, endIndex);
            string selectedText = textRange.Text;
            if (string.IsNullOrWhiteSpace(selectedText)) return;
            foreach (string item in _performers)
            {
                Regex regex = new(item);
                MatchCollection matches = regex.Matches(selectedText);
                foreach (Match match in matches)
                {
                    int start = startIndex + match.Index;
                    int end = start + item.Length;
                    ITextRange range = editor.Document.GetRange(start, end);
                    if (range.Text != item) continue;
                    ITextCharacterFormat charFormatting = range.CharacterFormat;
                    charFormatting.Bold = FormatEffect.On;
                    charFormatting.ForegroundColor = Colors.Red;
                }
            }
            foreach (string item in _regions)
            {
                Regex regex = new(item);
                MatchCollection matches = regex.Matches(selectedText);
                foreach (Match match in matches)
                {
                    int start = startIndex + match.Index;
                    int end = start + item.Length;
                    ITextRange range = editor.Document.GetRange(start, end);
                    if (range.Text != item) continue;
                    ITextCharacterFormat charFormatting = range.CharacterFormat;
                    charFormatting.Bold = FormatEffect.On;
                    charFormatting.ForegroundColor = Colors.Blue;
                }
            }
            foreach (string item in _spells)
            {
                Regex regex = new(item);
                MatchCollection matches = regex.Matches(selectedText);
                foreach (Match match in matches)
                {
                    int start = startIndex + match.Index;
                    int end = start + item.Length;
                    ITextRange range = editor.Document.GetRange(start, end);
                    if (range.Text != item) continue;
                    ITextCharacterFormat charFormatting = range.CharacterFormat;
                    charFormatting.Bold = FormatEffect.On;
                    charFormatting.ForegroundColor = Colors.Green;
                }
            }
            await Task.CompletedTask;
        }
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            foreach (object? item in RegionList.Items)
            {
                if (item is not string value) return;
                _regions.Add(value);
            }
            foreach (object? item in PerformerList.Items)
            {
                if (item is not string value) return;
                _performers.Add(value);
            }
            foreach (object? item in SpellList.Items)
            {
                if (item is not string value) return;
                _spells.Add(value);
            }
        }
        private void RichEditBoxKeyboardAccelerator_Invoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args)
        {
            if (_performers.Count > 0)
            {
                editor.Document.Selection.TypeText(_performers[0]);
            }
        }
    }
}
